package com.example.class1;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends ListActivity implements Runnable, View.OnClickListener {

    private Button btn1, btn2, btn3;
    EditText rmb;
    TextView show;
    Handler handler;
    float dollarRate = 0.0f;
    float euroRate = 0.0f;
    float wonRate = 0.0f;
    private static final String TAG = "Rate";
    Bundle bd;
    SharedPreferences sp;

    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        List<String> list1 = new ArrayList<String>();
        for (int i = 1; i < 100; i++) {
            list1.add("item" + 1);
        }
        String[] list_data = {"one", "two", "three", "four"};
        ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list_data);
        setListAdapter(adapter);
        setContentView(R.layout.activity_main);
        initView();
        SharedPreferences sharedPreferences = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);
        dollarRate = sharedPreferences.getFloat("dollar_rate", 0.0f);
        euroRate = sharedPreferences.getFloat("euro_rate", 0.0f);
        wonRate = sharedPreferences.getFloat("won_rate", 0.0f);
        Log.i(TAG, "onCreate:sp dollarRate=" + dollarRate);
        Log.i(TAG, "onCreate:sp euroRate=" + euroRate);
        Log.i(TAG, "onCreate:sp wonRate=" + wonRate);

        //Thread t = new Thread(this);
        // t.start();

        handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 5) {
                    List<String> list2 = (List<String>) msg.obj;
                    ListAdapter adapter = new ArrayAdapter<String>(
                            MainActivity.this,
                            android.R.layout.simple_list_item_1,
                            list2);
                    setListAdapter(adapter);
                }

                   Bundle bdl = (Bundle) msg.obj;
                    dollarRate = bdl.getFloat("web-dollar");
                    euroRate = bdl.getFloat("web-euro");
                    wonRate = bdl.getFloat("web-won");
                    show.setText("get web ok");

                    String lasttime = sp.getString("time", "0000-00-00");

                    String time = bdl.get("time").toString().substring(12, 22);

                    Log.i(TAG, lasttime + "and" + time);

                    if (!time.equals(lasttime)) {
                        editor = sp.edit();

                        editor.putFloat("dol", bdl.getFloat("美元"));

                        editor.putFloat("eur", bdl.getFloat("欧元"));

                        editor.putFloat("won", bdl.getFloat("韩元"));

                        editor.putString("time", time);

                        editor.apply();

                        Log.i(TAG, "已更新" + bdl.toString());

                    } else

                        Log.i(TAG, "同一天，不更新");


                super.handleMessage(msg);
            }
        };
    }







    private void initView() {
        btn1 = (Button) findViewById(R.id.btn1);
        btn2 = (Button) findViewById(R.id.btn2);
        btn3 = (Button) findViewById(R.id.btn3);
        rmb = (EditText) findViewById(R.id.tpn);
        show = (TextView) findViewById(R.id.result);


        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);

    }

    public void onClick(View btn) {
        String str = rmb.getText().toString();
        Log.i(TAG, "onCreate:...");
        float i = Float.parseFloat(str);

        if (str.length() == 0) {
            Toast.makeText(this, "请输入金额", Toast.LENGTH_SHORT).show();

        } else {

            float r = 0.0f;
            Log.i(TAG, "click:");
            if (btn.getId() == R.id.btn1) {
                show.setText(String.format("%.2f", r * dollarRate));
            } else if (btn.getId() == R.id.btn2) {
                show.setText(String.format("%.2f", r * euroRate));
            } else {
                show.setText(String.format("%.2f", r * wonRate));

            }

        }
    }

    public void openOne(View btn) {
        openConfig();
    }

    public void openConfig() {
        Intent config = new Intent(this, ConfigActivity.class);
        config.putExtra("dollar_rate_key", dollarRate);
        config.putExtra("euro_rate_key", euroRate);
        config.putExtra("won_rate_key", wonRate);
        Log.i(TAG, "open:dollar" + dollarRate);
        Log.i(TAG, "open:euro" + euroRate);
        Log.i(TAG, "open:won" + wonRate);
        startActivityForResult(config, 1);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.rate, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.menu) {
            openConfig();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 2) {

            Bundle bundle = data.getExtras();
            dollarRate = bundle.getFloat("key_dollar", 0.1f);
            euroRate = bundle.getFloat("key_euro", 0.1f);
            wonRate = bundle.getFloat("key_won", 0.1f);
            Log.i(TAG, "onActivityResult:dollarRate=" + dollarRate);
            Log.i(TAG, "onActivityResult:euroRate=" + euroRate);
            Log.i(TAG, "onActivityResult:wonRate=" + wonRate);
            sp = getSharedPreferences("myrate", Activity.MODE_PRIVATE);

            editor.putFloat("dollar_rate", dollarRate);
            editor.putFloat("euro_rate", euroRate);
            editor.putFloat("won_rate", wonRate);
            editor.commit();
            Log.i(TAG, "onActivityResult:数据已保存到sharedPreferences");


        }


    }

    public void run() {
       Log.i(TAG, "run:run().....");
        for (int i = 1; i < 3; i++) {
            Log.i(TAG, "run:i" + i);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        Message msg = handler.obtainMessage(5,bd);
       // msg.obj = "Hello from run()";
       // handler.sendMessage(msg);
        handler.sendMessage(msg);
        Log.i(TAG,"run:sendMessage ok");

      /* URL url= null;
        try {
            url = new URL("http://www.usd-cny.com/bankofchina.htm");
            HttpsURLConnection http= (HttpsURLConnection) url.openConnection();
            InputStream in=http.getErrorStream();
            String html=inputStream2String(in);
            Log.i(TAG,"run:html"+html);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        Document doc=null;
        try {
             doc = Jsoup.connect("http://www.usd-cny.com/bankofchina.htm").get();
            String title = doc.title();
            Log.i(TAG, "run:title=" + title);
            Elements tables=doc.getElementsByTag("table");
            Element table=tables.first();
            Elements tds = table.getElementsByTag("td");
            Elements ps=doc.getElementsByTag("p");
            Element p=ps.get(0);
            bd.putString("time",p.text());
            for (int i = 0; i < tds.size(); i += 8) {
                Element td1=tds.get(i);
                Element td2=tds.get(i+5);

                String str1=td1.text();
                String va1=td2.text();
                Log.i(TAG,"run:"+str1+"==>"+va1);

                float v=100f/Float.parseFloat(va1);}
                Log.i(TAG, "time"+p.text());//获取时间装入bundle
                Element dollartd = table.selectFirst( "tr:nth-child(27) > td:nth-child(6)");
                Element eurotd = table.selectFirst("tr:nth-child(9) > td:nth-child(6)");
                Element wontd = table.selectFirst("tr:nth-child(14) > td:nth-child(6)");
                Log.i(TAG, "run: web dollar: " + dollartd.text());
                Log.i(TAG, "run: web euro:" + eurotd.text());
                Log.i(TAG, "run: web won: " + wontd.text());
                bd.putFloat( "web-dollar" ,100f/Float.parseFloat(dollartd.text()));
                bd.putFloat("web-euro", 100f/Float.parseFloat(eurotd.text()));
                bd.putFloat("web-won", 100f/Float.parseFloat(wontd.text()));




            } catch(IOException e){
                e.printStackTrace();
            }



        


    }

    private String inputStream2String(InputStream inputStream) throws IOException {
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(inputStream, "gb2312");
        for (; ; ) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
        return out.toString();
    }

   
    }
